package student;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;

/*2.	使用DOM解析第1题 作业中编写的XML文档，输出所有学员信息，并进行以下操作：
删除id为1的学生成绩信息，修改id为2的成绩为60，添加一个学生的成绩信息（id为5）*/
public class DOMParserStudent {
    private static final String XML_PAHT = "homework26/src/student/scores.xml";
    private static DocumentBuilderFactory dbf = null;
    private static DocumentBuilder db = null;
    private static Document document = null;

    static {
        dbf = DocumentBuilderFactory.newInstance();
        try {
            db = dbf.newDocumentBuilder();
            document = db.parse(XML_PAHT);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //showAll();
        remove();
        modifier();
        add();
    }

    public static void showAll() {
        //先获取根元素节点
        Element rootElement = document.getDocumentElement();
        //再搜寻出所有的student子节点
        NodeList studentList = rootElement.getElementsByTagName("student");
        for (int i = 0; i < studentList.getLength(); i++) {
            Element stuElement = (Element) studentList.item(i);
            String id = stuElement.getAttribute("id");
            System.out.println(stuElement.getNodeName() + "：" + id);
            NodeList contentList = stuElement.getElementsByTagName("*");
            for (int j = 0; j < contentList.getLength(); j++) {
                Element content = (Element) contentList.item(j);
                if (content.getNodeType() == Node.ELEMENT_NODE) {
                    System.out.println(content.getNodeName() + ":" + content.getFirstChild().getNodeValue());
                    //请注意，元素中间那个内容（多数为文本）是该元素的子节点的值
                }
            }
        }
    }

    public static void saveXml(Document document) {
        TransformerFactory tf = TransformerFactory.newInstance();
        try {
            Transformer t = tf.newTransformer();
            DOMSource xmlSource = new DOMSource(document);
            t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            t.setOutputProperty(OutputKeys.INDENT, "yes");
            Result result = new StreamResult(new File(XML_PAHT));
            t.transform(xmlSource, result);
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }

    public static void add() {
        //添加一个节点最重要的是运用document中的create系列方法，要牢记
        Element rootElement = document.getDocumentElement();
        Element student = document.createElement("student");
        //设置属性
        student.setAttribute("id", "5");
        Element name = document.createElement("name");
        name.setTextContent("牛哥");
        Element course = document.createElement("course");
        course.setTextContent("数学");
        Element score = document.createElement("score");
        score.setTextContent("66");
        //注意使用appendChild()方法将一个元素节点加入到此节点最为子元素
        student.appendChild(name);
        student.appendChild(course);
        student.appendChild(score);
        rootElement.appendChild(student);//也要记得将student添加到根节点下，添加一直到根节点
        saveXml(document);
    }

    public static void remove() {
        Element rootEle = document.getDocumentElement();
        Element firstStudent = (Element) rootEle.getFirstChild().getNextSibling();
        //记得强转，因为后面得到是一个Node节点
        firstStudent.getParentNode().removeChild(firstStudent);
        saveXml(document);
    }

    public static void modifier(){
        Element root = document.getDocumentElement();
        NodeList studentList = root.getElementsByTagName("student");
        for (int i = 0; i < studentList.getLength(); i++) {
            Element tempStudent = (Element) studentList.item(i);
            if (tempStudent.getAttribute("id").equals("2")) {
                tempStudent.getLastChild().getPreviousSibling().setTextContent("60");
                break;
            }
        }
        saveXml(document);
    }
}
